from django.core.exceptions import ObjectDoesNotExist
from django.utils.crypto import get_random_string
from rest_framework import viewsets, status,generics
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
from rest_framework.response import Response
from .models import User, PasswordResetRequest
from django.contrib.auth.hashers import make_password, check_password
from .serializers import PasswordResetRequestSerializer, UserLoginSerializer,UserRegisterSerializer, RequestPasswordResetSerializer


class UserAuthViewSet(viewsets.ViewSet):
    @action(detail=False, methods=['post'])
    def login(self, request):
        """
        用户登录
        """
        serializer = UserLoginSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {'code': 400, 'message': '输入数据有误', 'errors': serializer.errors},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            # 仅通过用户名查询用户
            user = User.objects.get(username=serializer.validated_data['username'])

            # 验证密码
            if not check_password(serializer.validated_data['password'], user.password):
                return Response(
                    {'code': 401, 'message': '用户名或密码错误'},
                    status=status.HTTP_401_UNAUTHORIZED
                )

            # 可选：验证角色
            if 'role' in serializer.validated_data and user.role != serializer.validated_data['role']:
                return Response(
                    {'code': 403, 'message': '角色权限不足'},
                    status=status.HTTP_403_FORBIDDEN
                )

            # 登录成功
            return Response({
                'code': 200,
                'message': '登录成功',
                'data': {
                    'user_id': user.id,
                    'username': user.username,
                    'role': user.role
                }
            })

        except ObjectDoesNotExist:
            return Response(
                {'code': 404, 'message': '用户不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

    @action(detail=False, methods=['post'])
    def register(self, request):
        """
        用户注册
        """
        serializer = UserRegisterSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    'code': 400,
                    'message': '输入数据有误',
                    'errors': serializer.errors,
                    'data': None
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        if User.objects.filter(username=serializer.validated_data['username']).exists():
            return Response(
                {
                    'code': 400,
                    'message': '用户名已存在',
                    'data': None
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        user = User.objects.create_user(
            username=serializer.validated_data['username'],
            password=serializer.validated_data['password'],
            phone=serializer.validated_data.get('phone', ''),
            real_name=serializer.validated_data.get('real_name', ''),
            email=serializer.validated_data.get('email', ''),
            gender=serializer.validated_data.get('gender', '1'),
            role=serializer.validated_data.get('role', '1')
        )

        return Response({
            'code': 201,
            'message': '注册成功',
            'data': {
                'user_id': user.id,
                'username': user.username,
                'role': user.role  # 添加角色信息
            }
        }, status=status.HTTP_201_CREATED)

class RequestPasswordResetView(generics.CreateAPIView):
    serializer_class = RequestPasswordResetSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        # 验证用户信息
        try:
            user = User.objects.get(
                username=request.data.get('username'),
                email=request.data.get('email'),
                role=request.data.get('role')
            )
        except User.DoesNotExist:
            return Response(
                {'detail': '用户信息不匹配'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 创建重置请求
        token = get_random_string(50)
        reset_request = PasswordResetRequest.objects.create(
            user=user.username,
            token=token
        )

        return Response({
            'detail': '密码重置请求已提交',
            'request_id': reset_request.id
        }, status=status.HTTP_201_CREATED)

class ListResetRequestsView(generics.ListAPIView):
    serializer_class = PasswordResetRequestSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]

    def get_queryset(self):
        queryset = PasswordResetRequest.objects.all().select_related('user')
        status_filter = self.request.GET.get('status')

        if status_filter == 'pending':
            queryset = queryset.filter(is_processed=False)
        elif status_filter == 'processed':
            queryset = queryset.filter(is_processed=True)

        return queryset.order_by('-created_at')


class ProcessResetRequestView(generics.GenericAPIView):
    permission_classes = [IsAuthenticated, IsAdminUser]

    def post(self, request, request_id, *args, **kwargs):
        try:
            reset_request = PasswordResetRequest.objects.get(id=request_id)
        except PasswordResetRequest.DoesNotExist:
            return Response(
                {'detail':'未找到该重置申请'},
                status=status.HTTP_404_NOT_FOUND
            )

        actions = request.data.get('action')

        if action == 'approve':
            # 同意重置密码
            default_password = request.data.get('default_password', '12345678')
            reset_request.user.set_password(default_password)
            reset_request.user.save()

            reset_request.is_processed = True
            reset_request.save()

            return Response({
                'detail': f'密码已重置为 {default_password}',
                'user': {
                    'username': reset_request.user.username,
                    'email': reset_request.user.email
                }
            })

        elif action == 'reject':
            # 拒绝重置请求
            reset_request.is_processed = True
            reset_request.save()

            return Response({
                'detail': '已拒绝该密码重置申请',
                'user': {
                    'username': reset_request.user.username,
                    'email': reset_request.user.email
                }
            })

        else:
            return Response(
                {'detail':'无效的操作类型'},
                status=status.HTTP_400_BAD_REQUEST
            )
